package com.ygp.pool;

import java.util.concurrent.RecursiveTask;

/**
 * <Description> <br>
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2021/09/23 <br>
 */
public class CountTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 2; // 阈值

    public CountTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    private int start;
    private int end;

    @Override
    protected Integer compute() {
        int sum = 0; // 如果任务足够小就计算任务
        boolean canCompute = (end - start) <= THRESHOLD;

        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            int middle = (start + end) / 2;
            CountTask leftTask = new CountTask(start, middle);
            CountTask rightTask = new CountTask(middle + 1, end);
            leftTask.fork();
            rightTask.fork();
            int leftResult = leftTask.join();

            int rightResult = rightTask.join();
            sum = leftResult + rightResult;
        }
        return sum;
    }
}
